package bean.dao;

import hbt.HibernateUtil;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import dominio.*;

public class HibernateFacturaDAO {
	private static HibernateFacturaDAO instancia = null;
	private static SessionFactory sf = null;
	private Session session = null;

	public static HibernateFacturaDAO getInstancia() {
		if (instancia == null) {
			sf = HibernateUtil.getSessionFactory();
			instancia = new HibernateFacturaDAO();
		}
		return instancia;
	}

	private Session getSession() {
		if (session == null)
			session = sf.openSession();
		return session;
	}

	public void closeSession() {
		if (session != null)
			session.close();
	}

	public void crearFactura (Factura f) {
		Session s = getSession();
		s.beginTransaction();		
		Remito r = (Remito)s.load(Remito.class, f.getRemito().getRemitoId());		
		Cliente c = (Cliente)s.load(Cliente.class,f.getCliente().getClienteId());
		FormaPago fp = (FormaPago)s.load(FormaPago.class, f.getFormaPago().getFormaPagoId());
		f.setRemito(r);
		f.setCliente(c);
		f.setFormaPago(fp);
		f.setNumero(r.getNumero());
		s.persist(f);
		s.flush();
		s.getTransaction().commit();

	}

	public void eliminarFactura (Factura f) {
		Session s = getSession();
		s.beginTransaction();
		s.delete(f);
		s.flush();
		s.getTransaction().commit();
	}

	public Factura loadFactura (Factura f) {
		Session s = this.getSession();
		s.load(f,f.getFacturaId());
		return f;

	}

	@SuppressWarnings("unchecked")
	public List<Factura> listarFacturas () {
		Session s = this.getSession();
		return (List<Factura>) s.createQuery("select s from Factura s").list();
	}


	public Factura buscarFactura (int id) {
		Session s = getSession();
		Factura f = (Factura) s.createQuery("select pai from Factura pai where pai.facturaId= '"+id+"'").uniqueResult();
		return f;
	}
	
	public Factura buscarFacturaPorNro (int num) {
		Session s = getSession();
		Factura f = (Factura) s.createQuery("select pai from Factura pai where pai.numero= '"+num+"'").uniqueResult();
		s.clear();
		return f;
	}
	
}
